home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / SNIP0492.ARJ / GETSTRNG.C < prev    next >
C/C++ Source or Header  |  1991-09-23  |  1KB  |  47 lines

  1. /*
  2. ** GETSTRNG.C -- Demonstation of dynamic memory allocation to
  3. **               receive string of unknown length.
  4. ** Ron Sires 1/31/89, released to the public domain.
  5. */
  6.  
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9.  
  10. #define BLOCKSIZ    16
  11.  
  12. char *getstring(void)
  13.  
  14. /* Be sure to free the char * you get from getstring()!!)  */
  15. {
  16.     int   i, bufsize=BLOCKSIZ, newchar;
  17.     char *buffer, *newbuf;
  18.  
  19.     /* Get initial BLOCKSIZ buffer to receive string.   */
  20.     if ((buffer = (char *) malloc(BLOCKSIZ)) == NULL)
  21.     {
  22.         puts("No room in memory for string.");
  23.         return NULL;
  24.     }
  25.     /* Get chars from keyboard and put them in buffer.  */
  26.     for (i = 0; ((newchar = getchar()) != EOF) && (newchar != '\n')
  27.       && (newchar != '\r'); /* No revision part */ )
  28.     {
  29.         buffer[i++] = (char) newchar;
  30.         if (i >= bufsize - 1)
  31.         {
  32.             /* If buffer is full, resize it. */
  33.             newbuf = (char *) realloc(buffer, bufsize + BLOCKSIZ);
  34.             if (newbuf == NULL)
  35.             {
  36.                 puts("Not enough room in memory for string.");
  37.                 buffer[i] = '\0';  /* Add terminator to partial string */
  38.                 return buffer;
  39.             }
  40.             buffer = newbuf;
  41.             bufsize += BLOCKSIZ;
  42.         }
  43.     }
  44.     buffer[i] = '\0';   /* Tack on a null-terminator. */
  45.     return buffer;
  46. }
  47.